package com.contextor.magiccards.web.handlers.battle.impl;

import com.contextor.magiccards.game.game.GameBattleManager;
import com.contextor.magiccards.model.battle.Battle;
import com.contextor.magiccards.model.character.Personage;
import com.contextor.magiccards.model.errors.MagicCardsException;
import com.contextor.magiccards.web.handlers.AbstractTOHandler;
import com.contextor.magiccards.web.handlers.battle.BattleToHandler;
import com.contextor.magiccards.web.to.battle.BattleListTO;
import com.contextor.magiccards.web.to.battle.BattleTO;
import com.contextor.magiccards.web.to.battle.CombatTO;
import com.contextor.magiccards.web.to.user.PersonageTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

/**
 * User: sergey
 * Date: Mar 22, 2011 11:57:46 AM
 */
@Service
class BattleToHandlerImpl extends AbstractTOHandler implements BattleToHandler {
    @Autowired
    protected GameBattleManager battleManager;

    public BattleTO create(String uid) throws MagicCardsException {
        return new BattleTO(battleManager.create(uid));
    }

    public BattleListTO listBattles(String uid) throws MagicCardsException {
        checkUid(uid);
        final Collection<Battle> battles = battleManager.listReadyToPlay(uid);
        final BattleListTO result = new BattleListTO();
        result.list = new ArrayList<BattleTO>(battles.size());
        for (Battle battle : battles) {
            result.list.add(new BattleTO(battle));
        }
        return result;
    }

    public CombatTO joinBattle(String uid, PersonageTO personageTO, BattleTO battleTO) throws MagicCardsException {
        checkUid(uid);
        final Personage personage = personageTO.toModel();
        compareUids(uid, personage);
        final Battle battle = battleTO.toModel();
        checkUid(battle.getUid());
        return new CombatTO(battleManager.join(personage, battle));
    }
}
